﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data;
using System.IO;
using System.IO.Compression;
using System.Data.Entity.Infrastructure;
using System.Xml;
using System.Reflection;

namespace OpenWeb.Dal.DbCreation
{
  public class CreatePocoDb<TContext> : PopolaDb, IDatabaseInitializer<TContext>
          where TContext : DbContext
  {

      CreationEnum _condizione;
      bool _popola = false;

    public CreatePocoDb(CreationEnum pCondizione, bool pPopola)
	  {
          _condizione = pCondizione ;
          _popola = pPopola ;
	  }

      public void InitializeDatabase(TContext context)
      {
          switch (_condizione)
          {
              case CreationEnum.DropCreateAlways:
                  context.Database.Delete();
                  break;
              case CreationEnum.CreateOnlyIfNotExists:
                  if (context.Database.Exists())
                      return;
                  break;
              case CreationEnum.CreateOnlyIfModelChange:
                  if (context.Database.Exists() )
                      if (!context.Database.CompatibleWithModel(true))
                        context.Database.Delete();
                  else
                      return;
                  break;
              default:
                  break;
          }
    
          CreateDatabase(context);
        
      }


      private void CreateDatabase(TContext context)
      {
        try
        {
          // Create as much of the database as we can
          context.Database.Create();
          //context.Database.ExecuteSqlCommand("CREATE TABLE GLOBAL_DATA([KEY] VARCHAR(50), [VALUE] VARCHAR(250))");
          // No exception? Don't need a workaround

         PopolaIlDatabaseConDati(context);

          return;
        }
        catch (DataException ex)
        {
          throw;
        }

      }//fM

//    public void popola()
//    {

//        // Manually create the metadata table
//        var conn = ((SqlConnection)context.Database.Connection);
//        using (var command = conn.CreateCommand())
//        {
//          command.CommandText =
//          @"
//            CREATE TABLE __MigrationHistory (
//                MigrationId mediumtext NOT NULL,
//                Model mediumblob NOT NULL,
//                ProductVersion mediumtext NOT NULL);
// 
//            ALTER TABLE __MigrationHistory ADD PRIMARY KEY (MigrationId(255));
// 
//            INSERT INTO __MigrationHistory (
//                MigrationId,
//                Model,
//                ProductVersion)
//            VALUES (
//                'InitialCreate',
//                @Model,
//                @ProductVersion);
//            ";
//          command.Parameters.AddWithValue(
//              "@Model",
//              GetModel(context));
//          command.Parameters.AddWithValue(
//              "@ProductVersion",
//              GetProductVersion());

//          conn.Open();
//          command.ExecuteNonQuery();
//          conn.Close();
//        }



//      }//fm

      private byte[] GetModel(TContext context)
      {
        using (var memoryStream = new MemoryStream())
        {
          using (var gzipStream = new GZipStream(
              memoryStream,
              CompressionMode.Compress))
          using (var xmlWriter = XmlWriter.Create(
              gzipStream,
              new XmlWriterSettings { Indent = true }))
          {
            EdmxWriter.WriteEdmx(context, xmlWriter);
          }

          return memoryStream.ToArray();
        }
      }

      private string GetProductVersion()
      {
        return typeof(DbContext).Assembly
            .GetCustomAttributes(false)
            .OfType<AssemblyInformationalVersionAttribute>()
            .Single().InformationalVersion;
      }
    


  }
}
